import { Injectable } from '@nestjs/common';
import { InjectRepository, } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { User } from '../entity/user.entity';
import { Departments } from '../entity/departments.entity';
import { PageInit, PageNation } from 'src/interface/page.interface';
import { BaseQueryDto,QueryDto } from './../utils/baseQueryDto';
type T = any;
@Injectable()
export class DepartmentsService {

     constructor(
        @InjectRepository(Departments)
        private readonly departmentsRepository: Repository<Departments>,
        // @InjectRepository(User)
        // private readonly userRepository: Repository<User>,
     ) { }

     //创建机构
    async create(departments: Departments): Promise<any> {
        console.log(departments)

        return await this.departmentsRepository.save(departments);
    }
    //查找机构
     async findBy(departments: Departments): Promise<any> {
        // console.log(departments)
         return await this.departmentsRepository.findBy({
            userId:departments.userId
        });
     }
    //更新机构
    async update(departments: Departments,id:number): Promise<any> {
        // console.log(departments)

        return await this.departmentsRepository.update(id,departments)

    }
    //使用id查找机构
    async  findById(departments: Departments): Promise<any> {
        console.log(departments)
         return await this.departmentsRepository.findBy({
            id:departments.id
        });
    }

    //删除机构
    async  delete(id: number): Promise<any> {
          let one = await this.departmentsRepository.findOne({
                where: { id: id },
                withDeleted: true
            });
         return await this.departmentsRepository.softDelete(one.id);
     }
    async pageQuery(dto: QueryDto) {

    const { createName, pageSize=0, page } = dto;
    // 筛选状态为正常的数据
    const queryFilter: any = { status: 1 };
    if (createName) {
      // 模糊查询 createName
      queryFilter.createName = Like(`%${createName}%`);
    }
        console.log(queryFilter)
        console.log(pageSize)
    const res = await this.departmentsRepository.findAndCount({
      // 查询条件
      where: queryFilter,
      // 排序
    //   order: { updateTime: 'DESC' },
      // offset，分页的偏移量
      skip: (page - 1) * pageSize,
      // 每页条数
      take: pageSize,
      // 是否缓存
      cache: true,
    });
    console.log('4-5:',res)
    return loadPageQueryResult(res, pageSize);
  }

}
// 拼接返回结果的数据结构
export function loadPageQueryResult(findAndCountRes: any, pageSize: number) {
  const list = findAndCountRes[0];
  const totalCount = findAndCountRes[1];
    const totalPage = Math.ceil(totalCount / pageSize);

  return {
    list,
    totalCount,
    totalPage,
  };
}
